# coding:utf-8
from PyQt5.QtWidgets import QWidget
from src.globle import *
from qfluentwidgets import FluentIcon

from fuc_desktop.fuc_system.sys_messages_ui import Ui_sys_messages_ui

class sys_messages(Ui_sys_messages_ui, QWidget):

    def __init__(self, parent=None):
        super().__init__(parent=parent)
        self.setupUi(self)
        self.sys_info.clicked.connect(self.get_system_info)
        self.backup_log.clicked.connect(self.get_backup_log)
        self.sys_operation_info.clicked.connect(self.get_sys_operation_info)
    
    def get_system_info(self):
        options = self.execute_system_info()
        for key, value in options.items():
            self.TextEdit.append(f"{key}: {value}")

    def execute_system_info(self):
        run_sudo_command("su")
        commands = {
            "CPU型号": "sudo grep -m1 'model name' /proc/cpuinfo | awk -F: '{print $2}'",
            "系统版本": "sudo cat /etc/os-release | grep -w 'VERSION' | awk -F'=' '{print $2}'",
            "操作系统小版本号": "sudo cat /etc/kylin-build | grep -w 'Build' | awk -F' ' '{print $2}'",
            "服务序列号": "sudo kylin_serial",
            "注册码": "sudo kylin_gen_register",
            "激活码": "sudo cat /etc/.kyactivation",
            "主机序列号": "sudo cat /sys/class/dmi/id/product_serial",
            "硬盘序列号": "sudo udevadm info --query=all --name=/dev/$my_disk | grep ID_SERIAL= | cut -d'=' -f2 | sed 's/ /-/g'"
        }
        
        results = {}
        for key, cmd in commands.items():
            # 对于获取网卡MAC地址的命令，单独处理
            if key == "网卡MAC地址":
                phy_adapters = [phy_adapter for phy_adapter in os.listdir('/sys/class/net/') if phy_adapter not in os.listdir('/sys/devices/virtual/net/')]
                mac_addresses = [subprocess.check_output(["cat", f"/sys/class/net/{phy_adapter}/address"]).decode().strip() for phy_adapter in phy_adapters]
                results[key] = "\n".join(mac_addresses)
            else:
                # 使用 shell=True 来通过 shell 执行命令字符串
                result = subprocess.run(cmd, shell=True, text=True, capture_output=True)
                if result.returncode == 0:
                    results[key] = result.stdout.strip()
                else:
                    results[key] = f"Error: {result.stderr}"
        
        return results

    def get_backup_log(self):
        # run_sudo_command("su")
        time_stamp = datetime.now().strftime('%Y-%m-%d_%H-%M-%S')
        command=subprocess.run(["sudo", "tar", "-czvPf", f"/home/{local_user}/桌面/log_{time_stamp}.tar.gz", "/var/log"])
        result = subprocess.run(command, shell=True, text=True, capture_output=True)
        subprocess.run(["sudo", "chmod", "777", f"/home/{local_user}/桌面/log_{time_stamp}.tar.gz"])

        self.TextEdit.append(result.stdout)
        if result.stderr:
            self.TextEdit.append(result.stderr)
        notice=f"找到log_{time_stamp}.tar.gz这个文件，备份到桌面了，从桌面拷出来发给我\n"
        self.TextEdit.append(notice)

    def get_sys_operation_info(self):
        run_sudo_command("su")
        if os.path.exists(f"/home/{local_user}/桌面"):
            file_path = f"/home/{local_user}/桌面/stat_cpu_mem.txt"
        else:
            if os.path.exists(f"/home/{local_user}"):
                file_path = f"/home/{local_user}/stat_cpu_mem.txt"
            else:
                file_path = "/home/stat_cpu_mem.txt"

        with open(file_path, "a") as f:
            ps_cpu = subprocess.run(["ps", "aux", "--sort=-%cpu"], capture_output=True, text=True).stdout[:11]
            ps_mem = subprocess.run(["ps", "aux", "--sort=-%mem"], capture_output=True, text=True).stdout[:11]
            free_mem = subprocess.run(["free", "-h"], capture_output=True, text=True).stdout
            interrupts = subprocess.run(["cat", "/proc/interrupts"], capture_output=True, text=True).stdout
            f_ps_cpu = (f"占用cpu最高的10个进程是:{ps_cpu}")
            f_ps_mem = (f"占用mem最高的10个进程是:{ps_mem}")
            f_free_mem = (f"总体内存使用情况是:{free_mem}")
            f_interrupts = (f"中断情况是:{interrupts}")
            f_time=(f"{datetime.now()}")
            self.TextEdit.append(f_time)
            self.TextEdit.append(f_ps_cpu)
            self.TextEdit.append(f_ps_mem)
            self.TextEdit.append(f_free_mem)
            self.TextEdit.append(f_interrupts)